package com.mou.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mou.constant.MessageConstant;
import com.mou.constant.UserConstant;
import com.mou.context.BaseContext;
import com.mou.dto.*;
import com.mou.entity.Product;
import com.mou.entity.ProductFavorites;
import com.mou.entity.User;
import com.mou.exception.AccountErrorException;
import com.mou.exception.CategoryErrorException;
import com.mou.exception.ProductErrorException;
import com.mou.mapper.CategoryMapper;
import com.mou.mapper.ProductFavoritesMapper;
import com.mou.mapper.ProductMapper;
import com.mou.mapper.UserMapper;
import com.mou.result.PageResult;
import com.mou.result.Result;
import com.mou.service.ProductEsService;
import com.mou.service.ProductService;
import com.mou.vo.CategoryVO;
import com.mou.vo.ProductDetailVO;
import com.mou.vo.ProductVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service("productService")
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {

    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private ProductFavoritesMapper productFavoritesMapper;

    @Autowired
    private ProductEsService productEsService;

    @Override
    public PageResult pageQuery(ProductPageQueryDTO productPageQueryDTO) {
        PageHelper.startPage(productPageQueryDTO.getPage(), productPageQueryDTO.getPageSize());
        Page<Product> page = productMapper.pageQuery(productPageQueryDTO);
        long total = page.getTotal();
        List<Product> tempRecords = page.getResult();
        List<ProductVO> records = new ArrayList<>();
        for (Product p : tempRecords) {
            ProductVO productVO = new ProductVO();
            BeanUtils.copyProperties(p, productVO);
            if (p.getCategoryId() != null && p.getCategoryId()!=0) {
                productVO.setCategoryName(categoryMapper.selectById(p.getCategoryId()).getName());
            }else{
                productVO.setCategoryName("待分配");
            }
            if(p.getSellerId() != null && p.getSellerId()!=0){
                productVO.setSellerName(userMapper.selectById(p.getSellerId()).getNickname());
            }else{
                productVO.setSellerName("校园二手交易平台");
            }

            records.add(productVO);
        }
        return new PageResult(total, records);
    }

    @Override
    public List<ProductVO> getList() {
        List<Product> products = productMapper.getList();
        List<ProductVO> productVOS = new ArrayList<>();
        if (products != null) {
            for (Product p : products) {
                ProductVO productVO = new ProductVO();
                BeanUtils.copyProperties(p, productVO);
                if (p.getCategoryId() != null && p.getCategoryId()!=0) {
                    productVO.setCategoryName(categoryMapper.selectById(p.getCategoryId()).getName());
                }else{
                    productVO.setCategoryName("待分配");
                }
                if(p.getSellerId() != null && p.getSellerId()!=0){
                    productVO.setSellerName(userMapper.selectById(p.getSellerId()).getNickname());
                }else{
                    productVO.setSellerName("校园二手交易平台");
                }
                productVOS.add(productVO);
            }
        }
        return productVOS;
    }

    @Override
    public List<ProductVO> search(ProductSearchDTO productSearchDTO) {
        // 先把 category 名称转 id（若前端传 name）
        if (productSearchDTO != null && productSearchDTO.getCategory() != null) {
            Integer cid = categoryMapper.getIdByName(productSearchDTO.getCategory());
            productSearchDTO.setCategoryId(cid);
        }

        // 1) 优先使用 ES
        try {
            List<ProductVO> esList = productEsService.search(productSearchDTO);
            if (esList != null && !esList.isEmpty()) {
                // 补全 categoryName 和 sellerName（ES 只存 id）
                for (ProductVO vo : esList) {
                    if (vo.getCategoryId() != null && vo.getCategoryId() != 0) {
                        vo.setCategoryName(categoryMapper.selectById(vo.getCategoryId()).getName());
                    } else {
                        vo.setCategoryName("待分配");
                    }
                    if (vo.getSellerId() != null && vo.getSellerId() != 0) {
                        vo.setSellerName(userMapper.selectById(vo.getSellerId()).getNickname());
                    } else {
                        vo.setSellerName("校园二手交易平台");
                    }
                }
                return esList;
            }
        } catch (Exception e) {
            log.error("Elasticsearch 搜索异常，回退到数据库查询：{}", e);
            // 继续回退 DB
        }

        // 2) 回退到数据库（原有逻辑保持不变）
        List<ProductVO> productVOS = new ArrayList<>();
        if (productSearchDTO != null) {
            List<Product> products = productMapper.search(productSearchDTO);
            if (products != null) {
                for (Product p : products) {
                    ProductVO productVO = new ProductVO();
                    BeanUtils.copyProperties(p, productVO);
                    if (p.getCategoryId() != null && p.getCategoryId() != 0) {
                        productVO.setCategoryName(categoryMapper.selectById(p.getCategoryId()).getName());
                    } else {
                        productVO.setCategoryName("待分配");
                    }
                    if (p.getSellerId() != null && p.getSellerId() != 0) {
                        productVO.setSellerName(userMapper.selectById(p.getSellerId()).getNickname());
                    } else {
                        productVO.setSellerName("校园二手交易平台");
                    }
                    productVOS.add(productVO);
                }
            }
        }
        if (productVOS.isEmpty()) {
            throw new CategoryErrorException(MessageConstant.PRODUCT_NOT_FOUND);
        }
        return productVOS;
    }

    @Override
    public ProductDetailVO getDetailById(ProductDetailDTO productDetailDTO) {
        Product product = productMapper.selectById(productDetailDTO.getProductId());

        ProductDetailVO productDetailVO = new ProductDetailVO();
        BeanUtils.copyProperties(product, productDetailVO);

        if (productDetailVO.getCategoryId() != null && productDetailVO.getCategoryId()!=0) {
            productDetailVO.setCategoryName(categoryMapper.selectById(product.getCategoryId()).getName());
        }else{
            productDetailVO.setCategoryName("待分配");
        }
        User u = userMapper.selectById(product.getSellerId());
        if(productDetailVO.getSellerId() != null && productDetailVO.getSellerId()!=0){
            productDetailVO.setSellerName(u.getNickname());
            productDetailVO.setSellerAvatar(u.getAvatar());
        }else{
            productDetailVO.setSellerName("校园二手交易平台");
            productDetailVO.setSellerAvatar("https://wangmou-super.oss-cn-beijing.aliyuncs.com/8a0ab777-22f1-49a8-b33a-d378339e83c6.png");
        }

        if(productDetailDTO.getUserId() != null){
            ProductFavoritesDTO productFavoritesDTO = new ProductFavoritesDTO();
            productFavoritesDTO.setUserId(productDetailDTO.getUserId());
            productFavoritesDTO.setProductId(productDetailDTO.getProductId());
            ProductFavorites productFavorites = productFavoritesMapper.uniqueUserProductFavorites(productFavoritesDTO);
            if(productFavorites != null){
                productDetailVO.setProductFavorite(1);
            }else{
                productDetailVO.setProductFavorite(0);
            }
        }else {
            productDetailVO.setProductFavorite(0);
        }

        return productDetailVO;
    }

    @Override
    public void add(ProductUserDTO productUserDTO) {
//        Integer currentId = BaseContext.getCurrentId();
        Integer currentId = productUserDTO.getSellerId();
        User user = userMapper.selectById(currentId);
        if(productUserDTO.getTitle().isEmpty()||productUserDTO.getPrice()==0){
            throw new ProductErrorException(MessageConstant.PRODUCT_NOT_ADD);
        }
        if(user==null){
            throw new AccountErrorException(MessageConstant.SERVER_ERROR);
        }
        if(user.getRoleId()== UserConstant.USER_UNVERIFIED){
            throw new AccountErrorException(MessageConstant.UNAUTHENTICATED_USER);
        }
        Product product = Product.builder()
                .title(productUserDTO.getTitle())
                .description(productUserDTO.getDescription())
                .price(productUserDTO.getPrice())
                .imageUrl(productUserDTO.getImageUrl())
                .categoryId(0)
                .isCarousel(0)
                .sellerId(currentId)
                .status(3)
                .deleted(0)
                .createTime(LocalDateTime.now())
                .updateTime(LocalDateTime.now())
                .build();
        productMapper.add(product);
    }

    @Override
    public List<ProductVO> getMyProduct(Integer userId) {
        List<Product> products = productMapper.getByUserId(userId);
        List<ProductVO> productVOS = new ArrayList<>();
        if(products != null){
            for (Product p : products) {
                ProductVO productVO = new ProductVO();
                BeanUtils.copyProperties(p, productVO);
                if (p.getCategoryId() != null && p.getCategoryId()!=0) {
                    productVO.setCategoryName(categoryMapper.selectById(p.getCategoryId()).getName());
                }else{
                    productVO.setCategoryName("待分配");
                }
                if(p.getSellerId() != null && p.getSellerId()!=0){
                    productVO.setSellerName(userMapper.selectById(p.getSellerId()).getNickname());
                }else{
                    productVO.setSellerName("校园二手交易平台");
                }
                productVOS.add(productVO);
            }
        }
        return productVOS;
    }
}
